/*
 * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.luxor.sdk.common.interceptor;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;

/**
 * 日志记录拦截器
 *
 * @author Mr.Yan
 */
public class TCLogInterceptor implements Interceptor {
    private final boolean debug;
    private final Log logger;

    public TCLogInterceptor(String name) {
        this(name, false);
    }

    public TCLogInterceptor(String name, boolean isDebug) {
        logger = LogFactory.getLog(name);
        this.debug = isDebug;
    }

    public void info(final String str) {
        if (debug) {
            logger.info(str);
        }
    }

    public void info(final String str, final Throwable t) {
        if (debug) {
            logger.info(str, t);
        }
    }

    public void debug(final String str) {
        if (debug) {
            logger.debug(str);
        }
    }

    public void debug(final String str, final Throwable t) {
        if (debug) {
            logger.debug(str, t);
        }
    }

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();
        String req = ("发送请求, request url: " + request.url() + ". request headers information: " + request.headers());
        req = req.replaceAll("\n", ";");
        this.info(req);
        Response response = chain.proceed(request);
        String resp = ("接收响应, response url: " + response.request().url() + ", response headers: " + response.headers() + ",response body information: " + response.body());
        resp = resp.replaceAll("\n", ";");
        this.info(resp);
        return response;
    }

}